using System;
using System.Collections.Generic;
using System.Text;
using PDSClient.Communication;
using PDSClient.Utils.IO;

namespace PDSClient.Simple.Impl
{
    class SimpleClientConnection : IClientConnection, IConnectionListener
    {
        private IClientConnectionListener ccl;
        private IConnection myHandle = null;

        public SimpleClientConnection(IClientConnectionListener listener)
        {
            ccl = listener;        
        }

        public void Disconnect()
        {
            if (myHandle == null)
            {
                Exception e = new Exception("Not connected");
                //logging logger.logThrow(Level.FINE, re, re.getMessage());
                throw e;
            }
            myHandle.Close();
        }

        public void SendMessage(byte[] message)
        {
            /*
            if (logger.isLoggable(Level.FINEST)) {
                logger.log(Level.FINEST, "send on {0}: {1}",
                myHandle, HexDumper.format(message));
            }
            */
            try
            {
                myHandle.SendBytes(message);
            }
            catch (Exception e)
            {
                //logging logger.logThrow(Level.FINE, e, "Send failed:");
                throw e;
            }
        }

        public void Connected(IConnection conn)
        {
            /*
            if (logger.isLoggable(Level.FINER))
            {
                logger.log(Level.FINER, "connected: {0}", conn);
            }
            */
            this.myHandle = conn;
            ccl.Connected(this);
        }
        public void Disconnected(IConnection conn)
        {
            /*
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "disconnected: {0}", conn);
            }
            */
            // assert conn.equals(this.myHandle);
            // TODO what is graceful?
            ccl.Disconnected(true, null);
        }

        public void ExceptionThrown(IConnection conn, Exception e)
        {
            /*
            if (logger.isLoggable(Level.WARNING)) {
                logger.logThrow(Level.WARNING, exception,
                        "exception on: {0}: ", conn);
            }  
            */
            //assert conn.equals(this.myHandle);
            // TODO should we take any action here?  Bubble this up
            // to the CCL somehow?
        }

        public void BytesReceived(IConnection conn, byte[] message)
        {
            /*
            if (logger.isLoggable(Level.FINEST)) {
                logger.log(Level.FINEST, "recv on {0}: {1}",
                    conn, HexDumper.format(message));
            }
            assert conn.equals(this.myHandle);  
            */
            ccl.ReceivedMessage(message);
        }
    }
}
